﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using Aandelendelen.Obs;
using Aandelendelen.Mail;
using Aandelendelen.Db;
using Aandelendelen.Caching;

namespace Aandelendelen.Controls
{
	public partial class BannerViewControl : BaseUserControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			this.SetProperties();
		}

		private void SetProperties()
		{
			Query query = new Query("s_adstodisplay");

			ResultSet resultSet = (ResultSet)query.Execute();

			if (resultSet.Count == 0)
			{
				return;
			}

			int row = this.ChooseAd(resultSet);

			int id = (int)resultSet[row, "Id"];

			this.DisplayAd(resultSet, row, id);

			this.UpdateViews(resultSet, row, id);
		}

		private void DisplayAd(ResultSet resultSet, int row, int id)
		{
			string imageUrl = (string)resultSet[row, "BannerUrl"];
			if (imageUrl == "adsense")
				this.Banner.isAdsense = true;
			else
			{
				this.Banner.adId = id;
				this.Banner.isAdsense = false;
				this.Banner.ImageUrl = (string)resultSet[row, "BannerUrl"];
				this.Banner.Text = (string)resultSet[row, "ToolTip"];
				this.Banner.TargetUrl = this.Server.UrlEncode(((string)resultSet[row, "TargetUrl"]));
				this.Banner.Attributes["rel"] = "nofollow";
			}
		}

		private void UpdateViews(ResultSet resultSet, int row, int id)
		{
			int views = (int)resultSet[row, "Views"];
			int maxViews = (int)resultSet[row, "MaxViews"];

			Query query = new Query("sp_updateviews", "id", id, OleDbType.Integer);
			query.Execute();

			views++;

			if (views >= maxViews)
				this.ExpireAd(id);
		}

		private void ExpireAd(int id)
		{
			Query query = new Query("sp_expiread", "id", id, OleDbType.Integer);
			query.Execute();

			this.SendExpireMail(id);
		}

		private void SendExpireMail(int id)
		{
			Query getUserQuery = new Query("s_userfromad", "id", id, System.Data.OleDb.OleDbType.Integer);

			ResultSet resultSet = (ResultSet)getUserQuery.Execute();

			if (resultSet.Count != 1)
				return;

			AdvertiserInfo userInfo = new AdvertiserInfo(resultSet);

			MailArguments mailArgs = MailArguments.MailArgs;
			mailArgs.Clear();

			DateTime dt = (DateTime)resultSet[0, "EndDate"];
			mailArgs["{aanhef}"] = userInfo.MailAanhef;
			mailArgs["{id}"] = id.ToString();
			mailArgs["{expiredate}"] = dt.ToString("dd-MM-yyyy, HH:mm:ss");
			mailArgs["{views}"] = resultSet[0, "Views"].ToString();
			mailArgs["{clicks}"] = resultSet[0, "Clicks"].ToString();

			EMail email = MailCache.GetMail("adexpired");
			email.Recipients = userInfo.Email;

			email.QueueSingle();
		}

		private int ChooseAd(ResultSet resultSet)
		{
			int sumPrio = this.GetSumPriorities(resultSet);

			CacheableRandom rnd = CacheableRandom.GetInstance();

			int rndNum = rnd.Next(sumPrio);

			int currentTot = 0;

			for (int i = 0; i < resultSet.Count; i++)
			{
				int prio = (int)(resultSet[i, "Priority"]);
				currentTot += prio;
				if (currentTot > rndNum)
				{
					return i;
				}
			}

			return resultSet.Count - 1;
		}

		private int GetSumPriorities(ResultSet resultSet)
		{
			int sum = 0;

			for (int i = 0; i < resultSet.Count; i++)
			{
				sum += (int)(resultSet[i, "Priority"]);
			}

			return sum;
		}
	}
}